﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.MaintenanceUpdates.CApMaintenanceUpdatesCmd
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using Microsoft.Win32;
using System;
using System.IO;
using System.Threading;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Threading;
using Tecnomatix.Engineering;
using Tecnomatix.Engineering.PrivateImplementationDetails;
using Tecnomatix.Engineering.Ui;


namespace DnProcessSimulateCommands.MaintenanceUpdates;

public class CApMaintenanceUpdatesCmd : TxButtonCommand
{
  private string _regKeyPath = "SOFTWARE\\Tecnomatix\\eMPower\\MaintenanceUpdates";
  private const string RECEIVE_NOTIFICATIONS_ENTRY = "ReceiveNotifications";
  private static TxRibbonNotificationBar _notificationBar;

  public virtual string Name => CApMaintenanceUpdatesResources.COMMAND_NAME;

  public virtual string Category => CApMaintenanceUpdatesResources.COMMAND_CATEGORY;

  public virtual string Tooltip => CApMaintenanceUpdatesResources.COMMAND_TOOLTIP;

  public virtual string Description => CApMaintenanceUpdatesResources.COMMAND_DESCRIPTION;

  public virtual ITxImage Image => (ITxImage) TxImageManager.GetImageByKey("CheckForUpdates");

  private string GetRegStringValue(string valueName)
  {
    RegistryKey registryKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32).OpenSubKey(this._regKeyPath);
    if (registryKey != null)
    {
      object obj = registryKey.GetValue(valueName);
      if (obj != null)
        return obj.ToString();
    }
    return (string) null;
  }

  private bool? GetRegBoolValue(string regValueName)
  {
    string regStringValue = this.GetRegStringValue(regValueName);
    bool result;
    return regStringValue != null && bool.TryParse(regStringValue, out result) ? new bool?(result) : new bool?();
  }

  private void DownloadUpdate(CApMaintenanceUpdatesApp app, VersionDeclarationEntry newVersionInfo)
  {
    string setup = newVersionInfo.Setup;
    if (!CApMaintenanceUpdatesApp.IsSetupUrlValid(setup))
      return;
    CUiMaintenanceUpdateDownloadWindow updateDownloadWindow = new CUiMaintenanceUpdateDownloadWindow(setup, false);
    ((Window) updateDownloadWindow).ShowDialog();
    if (updateDownloadWindow.DownloadedSuccessfully && CApMaintenanceUpdatesApp.VerifySha(updateDownloadWindow.DownloadedFilePath, newVersionInfo.Hash))
    {
      this.UpdateDownloadedMessageBox(app, newVersionInfo);
    }
    else
    {
      if (File.Exists(updateDownloadWindow.DownloadedFilePath))
        File.Delete(updateDownloadWindow.DownloadedFilePath);
      if (TxMessageBox.ShowModal(CApMaintenanceUpdatesResources.DOWNLOAD_INTERRUPTED, CApMaintenanceUpdatesResources.COMMAND_NAME, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
        return;
      this.DownloadUpdate(app, newVersionInfo);
    }
  }

  private void UpdateDownloadedMessageBox(
    CApMaintenanceUpdatesApp app,
    VersionDeclarationEntry newVersionInfo)
  {
    if (TxMessageBox.ShowModal(CApMaintenanceUpdatesResources.ALREADY_DOWNOADED, CApMaintenanceUpdatesResources.COMMAND_NAME, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
      return;
    string downloadLocation = app.GetSetupTargetDownloadLocation(newVersionInfo.Setup);
    if (string.IsNullOrEmpty(downloadLocation))
      return;
    app.RunSetup(downloadLocation);
  }

  private void UpdateDownloaded(
    CApMaintenanceUpdatesApp app,
    VersionDeclarationEntry newVersionInfo)
  {
    if (CApMaintenanceUpdatesCmd._notificationBar != null)
      return;
    CApMaintenanceUpdatesCmd._notificationBar = new TxRibbonNotificationBar($"\b{CApMaintenanceUpdatesResources.UPDATE_DOWNLOADED}\b \a{CApMaintenanceUpdatesResources.SEE_RELEASE_NOTES}\a", CApMaintenanceUpdatesResources.UPDATE_BUTTON, (TxRibbonNotificationBar.NotificationIcon) 1);
    CApMaintenanceUpdatesCmd._notificationBar.ButtonClick += (EventHandler) ((o, e) =>
    {
      CApMaintenanceUpdatesCmd._notificationBar.Hide();
      CApMaintenanceUpdatesCmd._notificationBar = (TxRibbonNotificationBar) null;
      string downloadLocation = app.GetSetupTargetDownloadLocation(newVersionInfo.Setup);
      if (string.IsNullOrEmpty(downloadLocation))
        return;
      app.RunSetup(downloadLocation);
    });
    CApMaintenanceUpdatesCmd._notificationBar.HyperlinkClick += (EventHandler<TxRibbonNotificationBar_HyperlinkClickEventArgs>) ((o, e) => CApMaintenanceUpdatesApp.OpenReleaseNotesUrl(newVersionInfo.ReleaseNotes));
    CApMaintenanceUpdatesCmd._notificationBar.CloseClick += (EventHandler) ((o, e) => CApMaintenanceUpdatesCmd._notificationBar = (TxRibbonNotificationBar) null);
    CApMaintenanceUpdatesCmd._notificationBar.Show();
  }

  private void ShowUpdateAvailable(
    CApMaintenanceUpdatesApp app,
    VersionDeclarationEntry newVersionInfo)
  {
    if (CApMaintenanceUpdatesCmd._notificationBar != null)
      return;
    CApMaintenanceUpdatesCmd._notificationBar = new TxRibbonNotificationBar($"\b{CApMaintenanceUpdatesResources.UPDATE_AVAILABLE}\b \a{CApMaintenanceUpdatesResources.SEE_RELEASE_NOTES}\a", CApMaintenanceUpdatesResources.DOWNLOAD_BUTTON, (TxRibbonNotificationBar.NotificationIcon) 1);
    CApMaintenanceUpdatesCmd._notificationBar.ButtonClick += (EventHandler) ((o, e) =>
    {
      CApMaintenanceUpdatesCmd._notificationBar.Hide();
      CApMaintenanceUpdatesCmd._notificationBar = (TxRibbonNotificationBar) null;
      this.DownloadUpdate(app, newVersionInfo);
    });
    CApMaintenanceUpdatesCmd._notificationBar.HyperlinkClick += (EventHandler<TxRibbonNotificationBar_HyperlinkClickEventArgs>) ((o, e) => CApMaintenanceUpdatesApp.OpenReleaseNotesUrl(newVersionInfo.ReleaseNotes));
    CApMaintenanceUpdatesCmd._notificationBar.CloseClick += (EventHandler) ((o, e) => CApMaintenanceUpdatesCmd._notificationBar = (TxRibbonNotificationBar) null);
    CApMaintenanceUpdatesCmd._notificationBar.Show();
  }

  private void ShowErrorMessage(string message)
  {
    int num = (int) TxMessageBox.ShowModal(message, CApMaintenanceUpdatesResources.COMMAND_NAME, MessageBoxButtons.OK, MessageBoxIcon.Hand);
  }

  private void HandleNotification(string configContent)
  {
    if (!CApMaintenanceUpdatesApp.IsConfigFileValid(configContent))
    {
      this.ShowNotAbleToConnectMessage();
    }
    else
    {
      CApMaintenanceUpdatesApp app = new CApMaintenanceUpdatesApp(configContent);
      VersionDeclarationEntry newVersionInfo;
      bool? nullable = app.IsNewVersion(out newVersionInfo);
      if (!nullable.HasValue)
      {
        this.ShowNotAbleToConnectMessage();
      }
      else
      {
        if (!nullable.Value)
          return;
        if (app.IsMaintenanceUpdateDownloaded(newVersionInfo))
        {
          if (CApMaintenanceUpdatesApp.DoesMaintenanceUpdateFailed())
            this.ShowUpdateInstallationFailed(app, newVersionInfo);
          else
            this.UpdateDownloaded(app, newVersionInfo);
        }
        else
          this.ShowUpdateAvailable(app, newVersionInfo);
      }
    }
  }

  private void ShowUpdateInstallationFailed(
    CApMaintenanceUpdatesApp app,
    VersionDeclarationEntry newVersionInfo)
  {
    if (CApMaintenanceUpdatesCmd._notificationBar != null)
      return;
    CApMaintenanceUpdatesCmd._notificationBar = new TxRibbonNotificationBar($"\b{CApMaintenanceUpdatesResources.UPDATE_FAILED_MESSAGE}\b", CApMaintenanceUpdatesResources.RETRY_BUTTON, (TxRibbonNotificationBar.NotificationIcon) 2);
    CApMaintenanceUpdatesCmd._notificationBar.ButtonClick += (EventHandler) ((o, e) =>
    {
      CApMaintenanceUpdatesCmd._notificationBar.Hide();
      CApMaintenanceUpdatesCmd._notificationBar = (TxRibbonNotificationBar) null;
      string downloadLocation = app.GetSetupTargetDownloadLocation(newVersionInfo.Setup);
      if (string.IsNullOrEmpty(downloadLocation))
        return;
      app.RunSetup(downloadLocation);
    });
    CApMaintenanceUpdatesCmd._notificationBar.CloseClick += (EventHandler) ((o, e) => CApMaintenanceUpdatesCmd._notificationBar = (TxRibbonNotificationBar) null);
    CApMaintenanceUpdatesCmd._notificationBar.Show();
  }

  private void ShowNotAbleToConnectMessage()
  {
    string str = $"\b{CApMaintenanceUpdatesResources.CHECK_FOR_UPDATES_FAILED}\b";
    if (CApMaintenanceUpdatesCmd._notificationBar != null)
      return;
    CApMaintenanceUpdatesCmd._notificationBar = new TxRibbonNotificationBar(str, CApMaintenanceUpdatesResources.RETRY_BUTTON, (TxRibbonNotificationBar.NotificationIcon) 2);
    CApMaintenanceUpdatesCmd._notificationBar.ButtonClick += (EventHandler) ((o, e) =>
    {
      CApMaintenanceUpdatesCmd._notificationBar.Hide();
      CApMaintenanceUpdatesCmd._notificationBar = (TxRibbonNotificationBar) null;
      this.HandleMaintenanceNotification();
    });
    CApMaintenanceUpdatesCmd._notificationBar.CloseClick += (EventHandler) ((o, e) => CApMaintenanceUpdatesCmd._notificationBar = (TxRibbonNotificationBar) null);
    CApMaintenanceUpdatesCmd._notificationBar.Show();
  }

  private void HandleMaintenanceNotification()
  {
    Dispatcher mainDispatcher = Dispatcher.CurrentDispatcher;
    new Thread((ThreadStart) (() =>
    {
      string configContent;
      if (CApMaintenanceUpdatesApp.GetConfigFileContent(out configContent))
        mainDispatcher.InvokeAsync((Action) (() => this.HandleNotification(configContent)));
      else
        mainDispatcher.InvokeAsync((Action) (() => this.ShowNotAbleToConnectMessage()));
    })).Start();
  }

  public virtual void Execute(object cmdParams)
  {
    bool? regBoolValue = this.GetRegBoolValue("ReceiveNotifications");
    if (regBoolValue.HasValue && !regBoolValue.Value || CApMaintenanceUpdatesApp.IsMaintenanceUpdateRunning())
      return;
    this.HandleMaintenanceNotification();
  }
}
